CC := $(CROSS_COMPILE)gcc
CXX := $(CROSS_COMPILE)g++
AS := $(CROSS_COMPILE)as

BOARD_DIR := $(shell pwd)/..
PEER := root@172.17.0.198

CFLAGS += -Wall -Wextra

CFLAGS += -I.
CFLAGS += -Ithirdparty
CFLAGS += -Iapp
CFLAGS += -Idaemon
CFLAGS += -Iota

CFLAGS += -D_DEFAULT_SOURCE

ifdef DEBUG
	CFLAGS += -Og -ggdb
else
	CFLAGS += -O2 -g0 -z noexecstack
endif

ifdef SYSROOT
	CFLAGS += --sysroot=$(SYSROOT)
endif

LDFLAGS += -lpaho-mqtt3c
LDFLAGS += -lcurl
LDFLAGS += -lcrypto

SRC += $(shell find app -name "*.c"	-type f)
SRC += $(shell find daemon -name "*.c"	-type f)
SRC += $(shell find ota -name "*.c"	-type f)
SRC += $(shell find thirdparty -name "*.c"	-type f)

OBJ := $(SRC:.c=.o)

TARGET := gateway

.PHONY: all clean

all: $(TARGET)

clean:
	@rm -f $(TARGET) $(OBJ) main.o

$(TARGET): main.o $(OBJ)
	@$(CC) $(CFLAGS) $^ -o $@ $(LDFLAGS)

cross-compile:
	@CROSS_COMPILE=$(BOARD_DIR)/toolchain/bin/arm-linux-gnueabihf- \
		SYSROOT=$(BOARD_DIR)/sysroot \
		make -j16

cross-debug:
	@CROSS_COMPILE=$(BOARD_DIR)/toolchain/bin/arm-linux-gnueabihf- \
		SYSROOT=$(BOARD_DIR)/sysroot \
		DEBUG=true \
		make -j16

cross-copy: cross-compile init/S99gateway
	@scp -O $(TARGET) $(PEER):/usr/bin/$(TARGET)
	@scp -O init/S99gateway $(PEER):/etc/init.d/S99gateway

ssh-key:
	@echo "正在生成密钥对，如果出现覆盖提示，请同意..."
	@test -f ~/.ssh/id_rsa.pub && echo "密钥对已经存在" || ssh-keygen -t rsa -f ~/.ssh/id_rsa -N ""
	@echo "正在将公钥保存到开发板..."
	@ssh $(PEER) "cat /root/.ssh/authorized_keys" | \
		grep -Fxf ~/.ssh/id_rsa.pub | \
		wc -l | \
		xargs test 0 -eq && \
		ssh $(PEER) "mkdir -p /root/.ssh && cat >> /root/.ssh/authorized_keys" < ~/.ssh/id_rsa.pub || \
		echo "公钥已经存在"

cross-debug-run:
	@ssh $(PEER) "nohup gdbserver 0.0.0.0:2000 /usr/bin/$(TARGET) >/dev/null 2>&1 &"

%.o: %.c %.h
	@$(CC) $(CFLAGS) -c $< -o $@

%.o: %.cpp %.h
	@$(CXX) $(CXXFLAGS) -c $< -o $@

%.o: %.s
	@$(AS) $(ASFLAGS) -c $< -o $@

%_test: test/%_test.o $(OBJ)
	@$(CC) $(CFLAGS) $^ -o $@ $(LDFLAGS)
	@./$@
	@rm $@ $^

